#!/usr/bin/env bash

###############################################################################
# Copyright (c) 2017, 2022 Red Hat Inc and others
#
# This program and the accompanying materials are made
# available under the terms of the Eclipse Public License 2.0
# which is available at https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#     Red Hat Inc - initial API and implementation
#     Eurotech
###############################################################################

#
# This script deploys Keycloak and activates it in Kapua
#

set -e

# Commons

. "${BASH_SOURCE%/*}/env"
. "${BASH_SOURCE%/*}/functions"
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
KEYCLOAK_IMAGE="keycloak:sso"

# Check for mail server configuration
# (note: not required, but if used, all the following parameters must be set)
if test -n "$SMTP_HOST" || test -n "$SMTP_USER" || test -n "$SMTP_PASSWORD" || test -n "$SMTP_FROM" ; then
  test -n "$SMTP_HOST" || die "'SMTP_HOST' not set"
  test -n "$SMTP_USER" || die "'SMTP_USER' not set"
  test -n "$SMTP_PASSWORD" || die "'SMTP_PASSWORD' not set"
  test -n "$SMTP_FROM" || die "'SMTP_FROM' not set"
fi

# Build the Keycloak image if missing
if [[ "$(docker images -q ${KEYCLOAK_IMAGE} 2> /dev/null)" == "" ]] ; then
  cd "${SCRIPT_DIR}/../../commons/sso/keycloak/"
  . "./build"
  :
fi

# Create the Keycloak project
. "${SCRIPT_DIR}/../openshift-common.sh"
${OC} login --username=${OPENSHIFT_USER} --password=${OPENSHIFT_PASS} ${OPENSHIFT_LOGIN_OPTS} &>/dev/null
if  ${OC} describe "project/${KEYCLOAK_PROJECT_NAME}" &>/dev/null ; then
  ${OC} delete project "${KEYCLOAK_PROJECT_NAME}" &>/dev/null
fi
if ! ${OC} new-project "${KEYCLOAK_PROJECT_NAME}" --display-name="Keycloak" ; then
  echo "Old \"${KEYCLOAK_PROJECT_NAME}\" project scheduled for deletion, waiting... "
  while ! ${OC} new-project "${KEYCLOAK_PROJECT_NAME}" --display-name="Keycloak"  &>/dev/null  ; do
    sleep 5
  done
  echo "New \"${KEYCLOAK_PROJECT_NAME}\" project created."
fi

# Create Keycloak
$OC process -n "$KEYCLOAK_PROJECT_NAME" -f "${BASH_SOURCE%/*}/keycloak-template.yml" \
    "KAPUA_CONSOLE_URL=$(kapua_url)" \
    "SMTP_HOST=$SMTP_HOST" \
    ${KEYCLOAK_ADMIN_PASSWORD:+KEYCLOAK_ADMIN_PASSWORD=${KEYCLOAK_ADMIN_PASSWORD}} \
    "SMTP_PORT=$SMTP_PORT" \
    "SMTP_USER=$SMTP_USER" \
    "SMTP_PASSWORD=$SMTP_PASSWORD" \
    "SMTP_FROM=$SMTP_FROM" \
    "SMTP_ENABLE_SSL=$SMTP_ENABLE_SSL" \
    $@ | $OC create -n "$KEYCLOAK_PROJECT_NAME" -f -

exec ${BASH_SOURCE%/*}/activate
